package com.ecar.api.support.util;

import com.ecar.common.cipher.DES;
import com.ecar.common.util.StringUtil;

import java.util.Random;

/**
 * 密码工具类
 * Created by admin on 2016/6/20.
 */
public class PasswordUtil {

	/**
	 * 生成6-22位之内的随机字符串
	 * @param length 字符串长度，6-22
	 * @return
	 */
	public static String generate(int length) {
		length = length < 6 ? 6 : (length > 22 ? 22 : length);
		String str = "abcdefghijklmnopqrstuvwxyz23456789";
		Random random = new Random();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int num = random.nextInt(str.length());
			buf.append(str.charAt(num));
		}
		return buf.toString();
	}

	/**
	 * DES加密密码
	 * @param password
	 * @return
	 */
	public static String desencode(String password) {
		String key = Props.getValue("security.pwd.key");
		return DES.encrypt(key, password);
	}

	/**
	 * DES解密密码
	 * @param password
	 * @return
	 */
	public static String desdecode(String password) {
		String key = Props.getValue("security.pwd.key");
		return DES.decrypt(key, password);
	}

	/**
	 * 验证密码是否正确
	 * @param raw
	 * @param encrypted
	 * @return
	 */
	public static boolean eq(String raw, String encrypted) {
		return !(StringUtil.isEmpty(raw) && StringUtil.isEmpty(encrypted)) && raw.equals(desdecode(encrypted));
	}
}
